package com.wangjiang.mario.admin.system.domain.components;

import com.wangjiang.mario.admin.common.util.CommonUtils;
import com.wangjiang.mario.admin.system.domain.entity.SystemConfigEntity;
import com.wangjiang.mario.admin.system.domain.service.SystemConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 享元模式，利用commandLineRunner来从数据库中拉取初始系统配置变量
 * 全局配置，项目启动时从数据库中读取
 */
@Component
public class ConfigComponent implements CommandLineRunner {

    private final static Logger logger = LoggerFactory.getLogger(ConfigComponent.class);

    // 系统配置缓存
    private ConcurrentMap<String, String> configCache = new ConcurrentHashMap();

    @Autowired
    private SystemConfigService systemConfigService;

    @Override
    public void run(String... args) {
        List<SystemConfigEntity> configList = (List<SystemConfigEntity>) systemConfigService.baseList();
        setConfigListToConfigCache(configList);
    }

    /**
     * 将list存储到 缓存中
     *
     * @param configList
     */
    private void setConfigListToConfigCache(List<SystemConfigEntity> configList) {
        if (CommonUtils.isNotNull(configList)) {
            for (SystemConfigEntity config : configList) {
                configCache.put(config.getConfigKey(), config.getConfigValue());
            }
        }
    }

    public String getConfig(String key) {
        // 先从缓存中找，如果没有 从数据库中找
        String value;
        if (configCache.containsKey(key)) {
            value = configCache.getOrDefault(key, "");
        }
        // 不然从数据库中找
        else {
            value = systemConfigService.getValueByKey(key);
            cache(key, value);
        }

        logger.info("获取key:{}的值:{}", key, value);

        return value;
    }

    public String getUploadRootPath () {
        return getConfig("site.uploadPath");
    }

    public void cache(String key, String value) {
        configCache.put(key, value);
    }

    /**
     * 查看是否含有该key
     *
     * @param key
     * @return
     */
    public Boolean hasConfig(String key) {
        return configCache.containsKey(key);
    }
}
